<template>
  <a-layout style="height:100%">
    <a-layout-header style="display:flex;align-items:center;gap:12px;color:#fff">
      <span>BPMN 在线编辑</span>
      <a-input v-model:value="definitionKey" placeholder="流程定义 Key" style="width:180px" />
      <a-button @click="loadXml" type="primary" :loading="loading">加载</a-button>
      <a-button @click="deploy" :loading="deploying" type="primary" ghost>重新部署</a-button>
      <a-button @click="downloadXml">下载 XML</a-button>
    </a-layout-header>
    <a-layout-content style="position:relative">
      <div ref="canvasRef" style="height:calc(100vh - 64px);background:#fff"></div>
    </a-layout-content>
  </a-layout>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import Modeler from 'bpmn-js/lib/Modeler';
import { listDefinitions, getProcessDefinition, listDeploymentResources, getResourceXml, deployBpmn } from '../services/flowable';

const canvasRef = ref<HTMLDivElement | null>(null);
const modeler = ref<any>(null);
const definitionKey = ref('leaveApproval');
const loading = ref(false);
const deploying = ref(false);
let currentXml = '';

async function loadXml() {
  loading.value = true;
  try {
    // 找到最新版本的流程定义
    const defs = await listDefinitions();
    const target = defs.filter((d:any) => d.key === definitionKey.value).sort((a:any,b:any)=>b.version-a.version)[0];
    if (!target) { message.error('未找到流程定义'); return; }
    const deploymentId = target.deploymentId;
    const resources = await listDeploymentResources(deploymentId);
    const bpmnRes = resources.find((r:any) => r.name.endsWith('.bpmn20.xml'));
    if (!bpmnRes) { message.error('部署中未找到 BPMN 资源'); return; }
    currentXml = await getResourceXml(deploymentId, bpmnRes.id);
    if (!modeler.value) {
      modeler.value = new Modeler({ container: canvasRef.value });
    }
    await modeler.value.importXML(currentXml);
    message.success('加载成功');
  } catch (e:any) {
    message.error(e.message || '加载失败');
  } finally {
    loading.value = false;
  }
}

function downloadXml() {
  if (!modeler.value) { return; }
  modeler.value.saveXML({ format: true }).then((res:any) => {
    const blob = new Blob([res.xml], { type: 'text/xml' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `${definitionKey.value}.bpmn20.xml`;
    a.click();
    URL.revokeObjectURL(a.href);
  });
}

async function deploy() {
  if (!modeler.value) { message.error('尚未加载'); return; }
  deploying.value = true;
  try {
    const { xml } = await modeler.value.saveXML({ format: true });
    const file = new File([xml], `${definitionKey.value}.bpmn20.xml`, { type: 'text/xml' });
    await deployBpmn(file);
    message.success('重新部署成功');
  } catch (e:any) {
    message.error(e.message || '部署失败');
  } finally {
    deploying.value = false;
  }
}

</script>
<style scoped>
</style>
